package clientset

import (
	"context"

	"pdemo/bff/internal/infrastructure/conf"

	"pdemo/service-hello/api"

	"github.com/go-kratos/kratos/contrib/registry/etcd/v2"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware/logging"
	kgrpc "github.com/go-kratos/kratos/v2/transport/grpc"
	clientv3 "go.etcd.io/etcd/client/v3"
)

// ClientSet gRPC Client Set
type ClientSet struct {
	// 注入其他微服务客户端
	api.TemplateClient
}

// NewClientSet new gRPC Client Set
func NewClientSet(c *conf.Bootstrap, logger log.Logger) (*ClientSet, func(), error) {
	ec, _ := clientv3.New(clientv3.Config{
		Endpoints: []string{c.Register},
	})
	registry := etcd.New(ec, etcd.Namespace("/"+c.Namespace))

	conn, err := kgrpc.DialInsecure(
		context.TODO(),
		kgrpc.WithEndpoint(c.Params.ServiceHello),
		kgrpc.WithDiscovery(registry),
		kgrpc.WithMiddleware(
			logging.Client(logger),
		),
	)
	if err != nil {
		return nil, nil, err
	}

	cancelFn := func() {
		conn.Close()
	}

	h := &ClientSet{
		// 连接其他微服务客户端
		TemplateClient: api.NewTemplateClient(conn),
	}

	return h, cancelFn, nil
}
